import { getProfile } from '@/utils/storage'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  // 利用路由的滚动行为 滚到顶部。 还有第1种，让window滚动到顶部 window.scroll({ top: 0 })
  // scrollBehavior: () => {
  //   return {
  //     top: 0
  //   }
  // },

  routes: [
    { path: '/', component: () => import('@/views/layout/index.vue'), children: [
      { path: '', component: () => import('@/views/home/index.vue') },
      { path: '/category/:id', component: () => import('@/views/category/index.vue') },
      // { path: '/category/sub/:id', component: () => import('@/views/category/components/Subindex.vue') },
      { path: '/category/sub/:id', component: () => import('@/views/category/sub.vue') },
      { path: '/goods/:id', component: () => import('@/views/goods/index.vue') },
      { path: '/cart', component: () => import('@/views/cart/index.vue') },
      { path: '/member/checkout', component: () => import('@/views/checkout/index.vue') },
      { path: '/member/pay', component: () => import('@/views/pay/index.vue') },
      { path: '/pay/callback', component: () => import('@/views/pay/callback.vue') },
      { path: '/member', component: () => import('@/views/member/layout/index.vue'), children: [
        { path: '', component: () => import('@/views/member/home/index.vue') },
        { path: 'order', component: () => import('@/views/member/order/index.vue') }
      ] }
    ] },
    { path: '/login', component: () => import('@/views/login/index.vue') }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.fullPath.startsWith('/cart' || 'member')) {

    const profile = getProfile()
    console.log('---', profile)

    // 判断是否登录
    if (profile.token) {
      next()
    } else {
      next(`/login?redirectUrl=${encodeURIComponent(to.fullPath)}`)
    }
  } else {
    next()
  }
})



export default router